package com.mhy.netsafe;

import android.annotation.TargetApi;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import com.elvishew.xlog.LogLevel;
import com.elvishew.xlog.XLog;
import androidx.multidex.MultiDex;
import com.mhy.netsafe.db.DaoMaster;
import com.mhy.netsafe.db.DaoSession;
import com.mhy.netsafe.db.SQLiteHelp;
import com.mhy.netsafe.utils.SharedPreferenceUtil;
import com.mhy.netsafe.utils.ToastUtil;
import com.mhy.netsafe.utils.glide.GlideImageLoader;
import com.mhy.toast.ToastUtils;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.tencent.mmkv.MMKV;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.util.concurrent.TimeUnit;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.ThemeConfig;
import okhttp3.OkHttpClient;

/**
 * 项目名 NetSafe
 * 所在包 com.mhy.netsafe
 * 作者 mahongyin
 * 时间 2019/8/11 14:26
 * 邮箱 mhy.work@qq.com
 * 描述 说明:
 */
public class MyApplication extends Application {
    private static MyApplication app;
    private SQLiteDatabase db;
    DaoMaster mDaoMaster;
    DaoSession mDaoSession;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    //add  多渠道打包 获取mate 配置的
    public static Context sContext;

    public static String getChannel(Context context) {
        sContext = context;
        String channel = "";
        PackageManager pm = sContext.getPackageManager();
        try {
            ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            String value = ai.metaData.getString("APP_CHANNEL");
            if (value != null) {
                channel = value;
            }
        } catch (Exception e) {
// 忽略找不到包信息的异常
        }
        return channel;
    }

    public static MyApplication getInstance() {
        if (app != null && app instanceof MyApplication) {
            return app;
        } else {
            app = new MyApplication();
            app.onCreate();
            return app;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        sContext = this;
        SharedPreferenceUtil.init(this, "BaseConfig");
        configurationGallerFinal();
        okHttp();
        //设置greenDao
        setDatabase();
        MMKV.initialize(this);
        ToastUtils.init(this);
        XLog.init(LogLevel.ALL);
        // LeakC // refWatcher = LeakCanary.install(this);
        refWatcher = setupLeakCanary();

        if (!BuildConfig.IS_DEBUG) {//正式
            CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(this);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "bugly";
            String channelName = "通知消息";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            createNotificationChannel(channelId, channelName, importance);
        }

    }

    // GreenDAO各应用对象的初始化
    private void setDatabase() {
        // 创建数据库
        // 通过 DaoMaster 的内部类 DevOpenHelper，你可以得到一个便利的 SQLiteOpenHelper 对象。
        // 可能你已经注意到了，你并不需要去编写「CREATE TABLE」这样的 SQL 语句，因为 greenDAO 已经帮你做了。
        // 注意：默认的 DaoMaster.DevOpenHelper 会在数据库升级时，删除所有的表，意味着这将导致数据的丢失。
        // 所以，在正式的项目中，你还应该做一层封装，来实现数据库的安全升级。
        // 此处baseConfig.db表示数据库名称 可以任意填写
        SQLiteHelp mHelper = new SQLiteHelp(this, "baseConfig.db", null);
        db = mHelper.getWritableDatabase();
        // 注意：该数据库连接属于 DaoMaster，所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }

    public SQLiteDatabase getDb() {
        return db;
    }

    public DaoMaster getmDaoMaster() {
        return mDaoMaster;
    }

    public DaoSession getmDaoSession() {
        return mDaoSession;
    }


    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager notificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }

    // 在自己的Application中添加如下代码
    public static RefWatcher getRefWatcher(Context context) {

        MyApplication application = (MyApplication) context
                .getApplicationContext();
        return application.refWatcher;
    }

    // 在自己的Application中添加如下代码
    private RefWatcher refWatcher;

    private RefWatcher setupLeakCanary() {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return RefWatcher.DISABLED;
        }
        return LeakCanary.install(this);
    }

    private void okHttp() {
        /*包含cookie
        //PersistentCookieStore //持久化cookie
        //SerializableHttpCookie //持久化cookie
        //MemoryCookieStore //cookie信息存在内存中
        // */
        //配置cookie
        CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cookieJar(cookieJar) //cookie
                .addInterceptor(new LoggerInterceptor("httpTAG"))
                .connectTimeout(50000L, TimeUnit.MILLISECONDS)
                .readTimeout(50000L, TimeUnit.MILLISECONDS)
                //其他配置
                .build();

        OkHttpUtils.initClient(okHttpClient);
//配置https  设置可访问所有的https网站
//        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
//        OkHttpClient okHttpClients = new OkHttpClient.Builder()
//                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
//                .cookieJar(cookieJar) //cookie
//                .addInterceptor(new LoggerInterceptor("httpTAG"))
//                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
//                .readTimeout(10000L, TimeUnit.MILLISECONDS)
//                .build();
//        OkHttpUtils.initClient(okHttpClients);

//        设置具体的证书
//        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(证书的inputstream, null, null);
//        OkHttpClient okHttpClients = new OkHttpClient.Builder()
//                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
//                .cookieJar(cookieJar) //cookie
//                .addInterceptor(new LoggerInterceptor("httpTAG"))
//                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
//                .readTimeout(10000L, TimeUnit.MILLISECONDS)
//         .build();
//        OkHttpUtils.initClient(okHttpClients);
////        双向认证
//        HttpsUtils.getSslSocketFactory(
//                证书的inputstream,
//                本地证书的inputstream,
//                本地证书的密码);

    }

    /**
     * GallerFinal配置
     */
    private void configurationGallerFinal() {
        //配置主题
        ThemeConfig themeConfig = new ThemeConfig.Builder().build();
        //配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true).setEnableCrop(true).setEnableEdit(true)
                .setEnablePreview(true).setEnableRotate(true).setCropSquare(true).build();
        ImageLoader imageLoader = new GlideImageLoader();
        //配置核心信息
        CoreConfig coreConfig = new CoreConfig.Builder(this, imageLoader, themeConfig)
                .setFunctionConfig(functionConfig).build();
        GalleryFinal.init(coreConfig);
    }
}